package mvc.controller;

import mvc.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

@Controller
public class ParamController {

    //通过ServletAPI获取请求参数
    @RequestMapping("/testServletAPI")
    //形参位置的request表示当前请求
    public String testServletAPI(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username=" + username + ",password=" + password);
        return "success";
    }

    //通过控制器方法的形参获取请求参数
    @RequestMapping("/testParam")
    public String testParam(
            //@RequestParam是将请求参数和控制器方法的形参创建映射关系
            @RequestParam(value = "user_name", required = false, defaultValue = "he") String username,
            String password,
            String[] hobby,
            //@RequestHeader是将请求头信息和控制器方法的形参创建映射关系
            @RequestHeader(value = "sayHaHa", required = true, defaultValue = "hello") String host,
            //@CookieValue是将cookie数据和控制器方法的形参创建映射关系
            @CookieValue("JSESSIONID") String JSESSIONIO) {
        //多个请求参数中出现多个重名的请求参数，可以再控制器方法的参数位置设置字符串类型或字符串数组接收此参数
        //若使用字符串类型的形参，最终结果为请求参数的每一个值之间使用逗号进行拼接
        System.out.println("username=" + username + ",password=" + password + ",hobby:" + Arrays.toString(hobby));
        System.out.println("host:" + host);
        System.out.println("JSESSIONID:" + JSESSIONIO);
        return "success";
    }

    //通过POJO获取请求参数
    @RequestMapping("/testBean")
    public String testBean(User user) {
        System.out.println(user);
        return "success";
    }
}
